package com.example.movie.data.cinema.model.vm

import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import cn.forward.androids.utils.ThreadUtil
import com.example.movie.R
import com.example.movie.common.constants.LoadingState
import com.example.movie.common.model.RequestResult
import com.example.movie.common.model.Result
import com.example.movie.data.cinema.model.CinemaRepository
import com.example.movie.data.cinema.model.vo.SeatVo

class SeatTableViewModel(val repository: CinemaRepository) : ViewModel() {

    private val _seatData = MutableLiveData<RequestResult<SeatVo>>()
    val seatData: MutableLiveData<RequestResult<SeatVo>> = _seatData

    fun loadSeatData(planId: Int) {
        var result: Result<SeatVo>? = null;
        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                if (msg.what == LoadingState.OK) {
                    if (result is Result.Success) {
                        _seatData.value = RequestResult(
                            success = (result as Result.Success<SeatVo>).data
                        )
                    } else {
                        _seatData.value = RequestResult(
                            error = R.string.request_fail
                        )
                    }
                }
            }
        }

        ThreadUtil.getInstance().execute {
            result = repository.loadSeatData(planId)
            val message = Message()
            message.what = LoadingState.OK
            handler.sendMessage(message)
        }

    }

}